// pages/cart/index.js
import { getSetting, chooseAddress, openSetting, showModal, showToast } from "../../utils/wx.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0
  },

  onShow(){
    // 地址信息：
    // address{
    //   "errMsg":"chooseAddress:ok",
    //   "userName":"张三",
    //   "nationalCode":"510000",
    //   "telNumber":"020-81167888",
    //   "postalCode":"510000",
    //   "provinceName":"广东省",
    //   "cityName":"广州市",
    //   "countyName":"海珠区",
    //   "detailInfo":"新港中路397号"
    // }
    const ad = wx.getStorageSync("address");

    this.setData({
      address: ad
    });

    const cart = wx.getStorageSync("cart") || [];
    
    this.setCart(cart);
  },

  /**
   * 点击获取收货地址
   */
  handleChooseAddress(){
    // console.log("获取、收货地址");

    getSetting().then(res1 => {
      console.log("res1",res1);
      const scopeAddress = res1.authSetting["scope.address"];
      if(scopeAddress === false){
        openSetting().catch(err => {console.log(err);});
      }
      chooseAddress().then(res2 => {
        console.log("res2",res2);
        // 存入缓存中
        res2.all = res2.provinceName + res2.countyName + res2.detailInfo;
        wx.setStorageSync("address", res2);
      })
      .catch(err => {console.log(err);});
    })
    .catch(err => {console.log(err);});
  },

  /**
   * 点击选中商品
   */
  handleItemChange(e){
    const goods_id = e.currentTarget.dataset.id;
    // console.log(goods_id);
    let {cart} = this.data;
    let index = cart.findIndex(el => el.goods_id === goods_id);
    cart[index].checked = !cart[index].checked;
    
    this.setCart(cart);
  },

  /**
   * 设置购物车状态
   */
  setCart(cart){
    let allChecked = true, totalPrice = 0, totalNum = 0;
    cart.forEach(element => {
      if(element.checked){
        totalPrice += element.num * element.goods_price;
        totalNum += element.num;
      }else{
        allChecked = false;
      }
    });
    //判断cart是否为空
    allChecked = cart.length != 0 ? allChecked : false;
    this.setData({
      cart,
      allChecked,
      totalPrice,
      totalNum
    });

    wx.setStorageSync("cart", cart);

  },

  /**
   * 点击底部全选
   */
  handleAllCheck(e){
    let {cart, allChecked} = this.data;
    allChecked = !allChecked;
    cart.forEach(el => el.checked = allChecked);
    this.setCart(cart);
  },

  /**
   * 点击商品加减按钮
   */
  handleItemNumEdit(e){
    const {operation, id} = e.currentTarget.dataset;
    // console.log(operation, id);
    let {cart} = this.data;
    const index = cart.findIndex(el => el.goods_id === id);
    if(cart[index].num === 1 && operation === -1){
      // wx.showModal({
      //   title: '提示',
      //   content: '是否要删除？',
      //   success: (res) => {
      //     if (res.confirm) {
      //       cart.splice(index, 1); //删除
      //       this.setCart(cart);
      //       console.log('用户点击确定')
      //     } else if (res.cancel) {
      //       console.log('用户点击取消')
      //     }
      //   }
      // });

      showModal({content: '是否要删除？'}).then(res => {
        if (res.confirm) {
          cart.splice(index, 1); //删除
          this.setCart(cart);
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }).catch(err => console.log(err));

    }else{
      cart[index].num += operation; //operation: -1 或 1
      this.setCart(cart);
    }

  },

  /**
   * 点击结算
   */
  handlePay(){
    const {address, totalNum} = this.data;
    if(!address.userName){
      showToast({title: '您还没有选择收货地址'});
      return;
    }
    if(totalNum === 0){
      showToast({title: '您还没有选购任何商品'});
      return;
    }
    //跳转到支付页面：
    wx.navigateTo({
      url: '/pages/pay/index'
    });
  }

})